package com.erp.config;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("userDetailsService") //注意，这个名字要和前面的SecurityConfig中注入UserDetailsService类的名字相同
public class MyUserDetailsService implements UserDetailsService {

    //UserDetails:系统默认的用户主体
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        //Step2：编写实现类，返回User对象，User对象有用户名、密码和操作权限
        /**
         * 这里通过查看User可以看到其构造方法中，需要传入用户名、密码、权限
         *     public User(String username, String password, Collection<? extends GrantedAuthority> authorities) {
         *         this(username, password, true, true, true, true, authorities);
         *     }
         * 其中，权限是一个GrantedAuthority类型集合，其工具类是AuthorityUtils
         * 强调：auths不能传null，必须有值，如果auths为null会报错：
         * org.springframework.security.authentication.InternalAuthenticationServiceException: Cannot pass a null GrantedAuthority collection
         * 在实际开发中，我们通过查询数据库得到账号密码和权限
         * 如果查不到，则抛出异常。查得到就返回数据
         *
         */
        //传入用户名、密码、权限
        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("admin");
        return new User("admin", new BCryptPasswordEncoder().encode("123456"), auths);
    }
}
